import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isMobilePhone } from 'class-validator';
import { getConnection, Repository } from 'typeorm';
import { CreateUserDto } from '../controllers/dto/create.user.dto';
import { UserEntity } from '../entities/user.entity';
import userConfig from '@src/config/user.config';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  /**
   * @description: 创建账号
   */
  async createUser(createUserDto: CreateUserDto): Promise<string> {
    const { username, mobile } = createUserDto;
    const queryConditionList = [];
    if (username) {
      queryConditionList.push('user.username = :username');
    }
    if (mobile) {
      queryConditionList.push('user.mobile = :mobile');
    }
    const queryCondition = queryConditionList.join(' OR ');
    const findUser: Pick<UserEntity, 'username' | 'mobile'> | undefined = await getConnection()
      .createQueryBuilder(UserEntity, 'user')
      .select(['user.username', 'user.mobile'])
      .andWhere(queryCondition, { username, mobile })
      .getOne();

    if (findUser) {
      const { username, mobile } = findUser;
      if (username) {
        return '创建失败，已经存在该用户';
      } else if (isMobilePhone(mobile, 'zh-CN')) {
        return '创建失败，已经存在该手机号';
      } else {
        return '创建失败';
      }
    } else {
      const user: UserEntity = this.userRepository.create({
        ...createUserDto,
        password: userConfig.defaultPassword,
      });
      await this.userRepository.save(user);
      return '创建成功';
    }
  }

  /**
   * @description: 根据用户名查询账号
   */
  async getUserByUsername(username: string): Promise<any | undefined> {
    console.log('走这里，a');
    return await this.userRepository.find({ where: 'username' });
  }
}
